//
//  CZAuthorViewController.swift
//  微博
//
//  Created by 霸气的刘吉庆 on 16/4/19.
//  Copyright © 2016年 ios. All rights reserved.
//

import UIKit

import SVProgressHUD
//设置对应的信息

let WB_APP_KEY = "3650639813"

let WB_APP_SER = "bb3afe6caa27b1d6ed240c0ab921bc5b"

let WB_APP_URL = "http://beta.acfun.tv/"

class CZAuthorViewController: UIViewController {

    
    override func loadView() {
        
        view = webView
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WB_APP_KEY)&redirect_uri=\(WB_APP_URL)"
        
        print(urlString)
        
        let url = NSURL(string: urlString)
        
        let request = NSURLRequest(URL: url!)
        
        
        webView.loadRequest(request)
        
        
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
        
        
        

        // Do any additional setup after loading the view.
    }
    
    func setupUI(){
        
        title = "登录"
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "didCancelButton")
        
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "didAutoAddButton")
        
        
        
    }
    
    //注意addTarget方法前面一定要加上@objc
   @objc private func didCancelButton(){
        
        //点击取消按钮,直接dissmiss
        
     dismissViewControllerAnimated(false, completion: nil)
        
        
        
        
    }
    
   @objc private func didAutoAddButton(){
        
        //点击自动登录
        
        //直接执行js的语句
        
        //js语句的实现 https://api.weibo.com/oauth2/authorize
        
        let jsString = "document.getElementById('userId').value='18251902597';document.getElementById('passwd').value='woaizm1314'"
        
        webView.stringByEvaluatingJavaScriptFromString(jsString)
        
        
        
        
        
        
        
        
    }
    
    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    //首先懒加载一个webView
    
    
    private lazy var webView:UIWebView = {
        
       
        let w = UIWebView()
        
        w.delegate = self
        
        return w
        
        
    }()
    
    
    
    
    

    
}



//实现代理方法,这个方法里面有什么呢
extension CZAuthorViewController: UIWebViewDelegate {
    
    
    //授权以后的内容https://www.baidu.com/?code=3e2b491beaa8e2d4ee1cfad9dd6d4492
    
    //这个是加载请求是调用的方法,如果返回值为no,代表这个请求不在加载
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
      
        //取到请求里面的url
        
        //上面直接判断
        
        guard let url = request.URL else {
            
            return false
            
        }
        
//        let reqUrl = request.URL
        
        //取出这个url所对应的字符串
        
        
        //判断url是否以我们的url开头
        
        if url.absoluteString.hasPrefix(WB_APP_URL) {
            //来到这,说明是以回调页开头
            
            //从url中获取code吗
            
            
            print(url.query)
            
            //query 代表url后面的参数
            
            if let q = url.query where q.containsString("code="){
                
                
                
            let code =  q.substringFromIndex("code=".endIndex)
                
//                print("\(code)+111111")
                
                
                //取得授权码,我们应该去获取access_token
                
                
                //这里我的天
                
//                CZUserAccountViewModel.sharedViewModel.loadAccessToken(code,finish: )
                
//                loadAccessToken(code)
                
                
                CZUserAccountViewModel.sharedViewModel.loadAccessToken(code, finish: { (isSuccess) -> () in
                    
                    if isSuccess {
                        
                        //这个代表登录成功,注意上面的这个方法,里面调用了多个方法,最后一次性返回success,这个success为真的话就是真的登录成功了
                        
                        print("登录成功")
                        
                        
                        
                        self.dismissViewControllerAnimated(true, completion: { () -> Void in
//                            let delegateOwn =  UIApplication.sharedApplication().delegate as? AppDelegate
//                            
//                            delegateOwn?.window?.rootViewController = CZWelcomeVC()
                            
//                            NSNotificationCenter.defaultCenter().postNotification(CZChangeRootVCNotification)
                            
                            
                            //没有参数代表的是welcome传过去的
                            NSNotificationCenter.defaultCenter().postNotificationName(CZChangeRootVCNotification, object: nil)
//                            
                        })
                        
                        
                        print("登录成功,切换控制器")
                        
                        
                        
                        
                        
                        
                    }else{
                        
                        
                        print("登录失败")
                        
                        
                    }
                    
                    
                    
                })
                
                //要监听什么时候登录完成,可以给viewModel传入一个闭包,在viewModel里面登录完成之后调用该闭包就可以了
                
                //代表真真的成功
                
                
                
                
                
            }
            
            return false
            
            
            
            
            
            
        }
      
        //判断是否是回调页
        
        return true
        
        
        
    }

    
    //这个方法是开始加载请求
    func webViewDidStartLoad(webView: UIWebView) {
        
        
        //开始加载的时候,使用SVPro
        
        SVProgressHUD.show()
        
    }
    
    //这个是完成加载请求
    func webViewDidFinishLoad(webView: UIWebView) {
        
        
        SVProgressHUD.dismiss()
        
    }
    
    //这个是加载出错
//    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
//        
//        
//    }
    
    
    
    
    
    
}
